package com.alex.service;

import com.alex.dao.OfflineMessage;
import com.alex.dao.OfflineMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author shufei
 */
@Service
public class TransactionalServiceImpl implements TransactionalService {

    @Autowired
    private OfflineMessageMapper messageMapper;

    @Autowired
    private ExecutorService executorService;

    private static Lock lock = new ReentrantLock();


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertAndFind() {
        OfflineMessage message = new OfflineMessage();
        message.setMessage("insertAndFind");
        message.setStatus(1);
        message.setUserId("TT");

        messageMapper.insert(message);

        executorService.execute(() -> find(message.getId()));
    }

    private void find(Long id) {
        OfflineMessage byId = messageMapper.findById(id);
        System.out.println(byId);
    }

    public static void main(String[] args) {
        testLock();
    }

    public static void testLock() {
        lock.lock();
        try {

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //lock.unlock();
        }
    }
}
